package com.zerosky.crm.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Date;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.springframework.web.multipart.MultipartFile;

import com.zerosky.crm.po.Employee;

/**
 * 文件上传工具类
 * 
 * @author kou
 * 
 */
public class MyFileUploadUtils {
	/**
	 * 文件上传
	 * 
	 * @param file upload
	 *            上传的文件
	 * @param path uploadFileName
	 *            上传的文件存放的路径
	 * @return
	 * @throws Exception
	 * @throws Exception
	 * @throws Exception
	 */
	public static String fileUpload(File upload, String uploadFileName,
			String path,HttpServletRequest request) throws Exception {
		int index = uploadFileName.lastIndexOf(".");
		String suffix = uploadFileName.substring(index + 1,
				uploadFileName.length());
		uploadFileName = new Date().getTime() + "." + suffix;
		/*String savePath = ServletActionContext.getServletContext().getRealPath(
				"/" + path + "/" + uploadFileName);*/
		/*File file=new File("D:\\"+path);
		if(!file.exists()){
			file.mkdirs();
		} 
		String  savePath = file+ "/" + uploadFileName;*/
		String savePath = request.getSession().getServletContext().getRealPath("/" + path + "/" + uploadFileName);
		FileInputStream fis = new FileInputStream(upload);
		FileOutputStream fos = new FileOutputStream(savePath);
		IOUtils.copy(fis, fos);
		fos.flush();
		fos.close();
		fis.close();
		return path + "/" + uploadFileName;

	}
	
	
	
	/***
     * 保存文件
     *
     * @param file
     * @return
     */
    @SuppressWarnings("unused")
	public static boolean saveFile(HttpServletRequest request, MultipartFile file,String path) {
        // 判断文件是否为空
        if (!file.isEmpty()) {
            try {
            	//SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
            	
            	int index = file.getOriginalFilename().lastIndexOf(".");
        		String suffix = file.getOriginalFilename().substring(index + 1,
        				file.getOriginalFilename().length());
        		String name =UUID.randomUUID().toString() + "." + suffix;
        		
        		request.setAttribute("picture", name); //把图片名称写在 request里面
                // 保存的文件路径(如果用的是Tomcat服务器，文件会上传到\\%TOMCAT_HOME%\\webapps\\YourWebProject\\upload\\文件夹中  )
                String filePath =request.getSession().getServletContext().getRealPath("/" + path + "/" +name);
                
                File saveDir = new File(filePath);
                if (!saveDir.getParentFile().exists())
                    saveDir.getParentFile().mkdirs();
                 
                // 转存文件
                file.transferTo(saveDir);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    }
    
    /***
     * 保存文件
     *
     * @param file
     * @return
     */
    @SuppressWarnings("unused")
	public static String saveFileName(HttpServletRequest request, MultipartFile file,String path) {
    	 // 判断文件是否为空
        if (!file.isEmpty()) {
            try {
            	//SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
            	
            	int index = file.getOriginalFilename().lastIndexOf(".");
        		String suffix = file.getOriginalFilename().substring(index + 1,
        				file.getOriginalFilename().length());
        		String name =UUID.randomUUID().toString() + "." + suffix;
        		
        		//request.setAttribute("picture", name); //把图片名称写在 request里面
                // 保存的文件路径(如果用的是Tomcat服务器，文件会上传到\\%TOMCAT_HOME%\\webapps\\YourWebProject\\upload\\文件夹中  )
                String filePath =request.getSession().getServletContext().getRealPath("/" + path + "/" +name);
                
                File saveDir = new File(filePath);
                if (!saveDir.getParentFile().exists())
                    saveDir.getParentFile().mkdirs();
                 
                // 转存文件
                file.transferTo(saveDir);
                return name;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return "";
    }
    
    public static void download(String filepath, HttpServletResponse response,HttpServletRequest request){  
        Employee user = (Employee) request.getSession().getAttribute("loginUser");
        if(user == null){  
            return;  
        }  
          
        File file = new File(filepath);  
        InputStream inputStream = null;  
        OutputStream outputStream = null;  
        byte[] b= new byte[1024];  
        int len = 0;  
        try {  
            inputStream = new FileInputStream(file);  
            outputStream = response.getOutputStream();  
              
            response.setContentType("application/force-download");  
            String filename = file.getName();  
            filename = filename.substring(36, filename.length());  
            response.addHeader("Content-Disposition","attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));  
            response.setContentLength( (int) file.length( ) );  
              
            while((len = inputStream.read(b)) != -1){  
                outputStream.write(b, 0, len);  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        }finally{  
            if(inputStream != null){  
                try {  
                    inputStream.close();  
                    inputStream = null;  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
            }  
            if(outputStream != null){  
                try {  
                    outputStream.close();  
                    outputStream = null;  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
            }  
        }  
    }  
}
